import {
  Injectable,
  Logger,
  OnModuleInit,
  OnModuleDestroy,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

/**
 * 初始化服务
 * 提供应用启动初始化和健康检查功能
 */
@Injectable()
export class InitService implements OnModuleInit, OnModuleDestroy {
  private readonly logger = new Logger(InitService.name);
  private isHealthy = false;

  constructor(private readonly configService: ConfigService) {}

  /**
   * 模块初始化
   */
  async onModuleInit() {
    this.logger.log('Initializing application...');

    try {
      await this.initializeServices();
      await this.performHealthCheck();

      this.isHealthy = true;
      this.logger.log('Application initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize application', error);
      throw error;
    }
  }

  /**
   * 模块销毁
   */
  async onModuleDestroy() {
    this.logger.log('Shutting down application...');

    try {
      await this.cleanup();
      this.logger.log('Application shutdown completed');
    } catch (error) {
      this.logger.error('Error during application shutdown', error);
    }
  }

  /**
   * 初始化服务
   */
  private async initializeServices() {
    // 这里可以初始化各种服务
    // 例如：数据库连接、Redis 连接、外部服务等
    this.logger.log('Initializing services...');

    // 模拟初始化过程
    await new Promise((resolve) => setTimeout(resolve, 100));

    this.logger.log('Services initialized');
  }

  /**
   * 执行健康检查
   */
  private async performHealthCheck() {
    this.logger.log('Performing health check...');

    const healthConfig = this.configService.get('health');

    if (healthConfig.startupCheckEnabled) {
      // 这里可以检查各种依赖服务的健康状态
      // 例如：数据库、Redis、外部 API 等

      const timeout = healthConfig.startupTimeoutMs || 5000;
      const startTime = Date.now();

      // 模拟健康检查
      await new Promise((resolve) => setTimeout(resolve, 100));

      const duration = Date.now() - startTime;

      if (duration > timeout) {
        throw new Error(`Health check timeout after ${duration}ms`);
      }

      this.logger.log(`Health check completed in ${duration}ms`);
    }
  }

  /**
   * 清理资源
   */
  private async cleanup() {
    // 这里可以清理各种资源
    // 例如：关闭数据库连接、清理缓存等
    this.logger.log('Cleaning up resources...');

    // 模拟清理过程
    await new Promise((resolve) => setTimeout(resolve, 100));

    this.logger.log('Resources cleaned up');
  }

  /**
   * 获取健康状态
   */
  getHealthStatus() {
    return {
      status: this.isHealthy ? 'healthy' : 'unhealthy',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
    };
  }

  /**
   * 检查是否健康
   */
  isApplicationHealthy(): boolean {
    return this.isHealthy;
  }
}
